package nin.ja;

import android.util.Log;

public class RenderQueue {
	//public static Object drawLock;
	
	private static final int MAX_QUEUE_SIZE = 64;
	private static final int NUMBER_OF_QUEUES = 2;
	private static final int STARTING_DRAW_QUEUE = 1;
	
	private GameRenderer renderer;
	private RenderableObjectPool pool;
	private RenderableObject[][] dbqueue;
	private int drawQueue; // Queue being used for drawing
	
	public RenderQueue(GameRenderer renderer){
		this.renderer = renderer;
		dbqueue = new RenderableObject[NUMBER_OF_QUEUES][MAX_QUEUE_SIZE];
		pool = new RenderableObjectPool(NUMBER_OF_QUEUES * MAX_QUEUE_SIZE);
		for(int i = 0; i < NUMBER_OF_QUEUES; ++i){
			for(int j = 0; j < MAX_QUEUE_SIZE; ++j){
				dbqueue[i][j] = null;
			}
		}
		drawQueue = STARTING_DRAW_QUEUE;
		//drawLock = new Object();
		
		Log.v("RenderSystem", "RenderSystem loaded");
	}
	
	public void swap(){ // Should block on GameRenderer, use drawLock as lock b/w the two
		synchronized(renderer.drawLock){
			//Log.v("RenderSystem", "RenderSystem owns drawLock");
			renderer.setDrawQueue(dbqueue[drawQueue]);
			//pool.clear();
			drawQueue = drawQueue == 1 ? 0 : 1;
			for(int i = 0; i < MAX_QUEUE_SIZE; ++i){
				dbqueue[drawQueue][i] = null;
			}
		}
	}
	
	public void add(DrawableObject dob, Vector position){
		//synchronized(drawLock){ // Concurrency issue with adding to RenderSystem?
			int loadQueue = drawQueue == 1 ? 0 : 1;
			//Log.v("RenderSystem", "Queue length: " + dbqueue[loadQueue].length);
			for(int i = 0; i < dbqueue[loadQueue].length; ++i){
				if(dbqueue[loadQueue][i] == null){
				//	Log.v("RenderSystem", "Position in queue: " + (i + 1));
					RenderableObject ro = new RenderableObject();
						//(RenderableObject)pool.allocate();
					ro.set(dob, position);
					dbqueue[loadQueue][i] = ro;
					break;
				}
			}
			//Log.v("RenderSystem", "Finished adding item to queue");
		//}
	}
	
	public RenderableObject[] getDrawQueue(){
		return dbqueue[drawQueue];
	}
	
 	public class RenderableObject{
		public DrawableObject dob;
		public Vector position;
		
		public RenderableObject(){
	
		}
		
		public void set(DrawableObject dob, Vector position){
			this.dob = dob;
			this.position = position;
		}
	}
 	
 	public class RenderableObjectPool extends ObjectPool{
 		public RenderableObjectPool(){
 			super();
 		}
 		
 		public RenderableObjectPool(int size){
 			super(size);
 		}
 		
 		public void clear(){
 			for(int i = 0; i < dbqueue[drawQueue].length; ++i){
 				if(!(dbqueue[drawQueue] == null)){
 					super.release(dbqueue[drawQueue][i]);
 					dbqueue[drawQueue][i] = null;
 				}
 			}
 		}
 	}
}
